from django.db import transaction
from django.shortcuts import render
from datetime import datetime
from django.utils.timezone import now
from rest_framework.response import Response
from rest_framework.views import APIView

from utils.redis_utils import RedisHelper
from .tasks import createOrder
# Create your views here.


class Seckill(APIView):
    @transaction.atomic  # 确保操作的原子性
    def post(self,request):
        redis = RedisHelper()
        goods_id = request.POST.get('goodsId')
        user_id = redis.get_cache(request.headers.get('Authorization', '').split(' ')[1])['id']
        goods_key = f'goods_detail:{goods_id}'
        stock_key = f'seckill_stock:{goods_id}'

        # lock_key = f'lock:seckill:{goods_id}'
        # lock_value = redis.acquire_lock(lock_key, expire_time=1)
        # try:
        # if not lock_value:
        #     return Response({'code': 400, 'message': '系统繁忙，请稍后重试'})
        goods = redis.get_cache(goods_key)
        stock = redis.get_cache(stock_key)
        if not goods or not goods['is_seckill']:
            return Response({'code': 400, 'message': '该商品不是活动商品'})
        if not ( datetime.fromisoformat(goods['start_date']) <=now() <=  datetime.fromisoformat(goods['end_date'])):
            return Response({'code': 400, 'message': '秒杀活动无效或已结束'})
        # 使用 Redis 的原子操作扣减库存
        # current_stock = redis.redis_client.decr(stock_key)
        # if current_stock < 0:
        #     redis.redis_client.incr(stock_key)  # 回滚库存
        lua_script = """
        local stock_key = KEYS[1]
        local current_stock = tonumber(redis.call("GET", stock_key))
        if current_stock and current_stock > 0 then
            redis.call("DECR", stock_key)
            return current_stock - 1
        else
            return -1
        end
        """

        result = redis.redis_client.eval(lua_script, 1, stock_key)
        if result == -1:
            return Response({'code': 400, 'message': '库存不足'})

        # 更新商品缓存
        goods['seckill_stock'] = result
        goods['stock_count'] -= 1
        redis.set_cache(goods_key, goods, timeout=3600)
        redis.set_cache(stock_key, result, timeout=3600)
        createOrder.delay(goods_id,user_id)
        # # 尝试扣减库存
        # remaining_stock = redis.decrement_stock(stock_key)
        # if remaining_stock <= 0:
        #     return Response({'code': 400, 'message': '库存不足'})
        #
        # # 更新商品缓存
        # goods['seckill_stock'] = remaining_stock
        # goods['stock_count'] -= 1
        # redis.set_cache(goods_key, goods, timeout=3600)
        # redis.set_cache(stock_key, remaining_stock, timeout=3600)
        # createOrder.delay(goods_id,user_id)
        return Response({'code':200,"message": "秒杀成功，订单正在处理中"})
        # finally:
        #     if lock_value:  # 确保 lock_value 有效
        #         redis.release_lock(lock_key, lock_value)
        #
        # redis.acquire_lock(stock_key)
        # if stock <= 0:
        #     return Response({'code': 400, 'message': '库存不足'})
        # stock-=1
        # goods['seckill_stock']-=1
        # redis.set_cache(goods_key,goods)
        # redis.set_cache(stock_key,stock)
        # redis.release_lock(stock_key)
        # redis.release_lock(goods_key)
        # except Exception as e:
        #
        #     return Response({'code': 500, 'message': f'系统错误：{str(e)}'})
        #
        # finally:
        #     redis.release_lock(lock_key, lock_value)

        # try:
        #
        #     # 查询商品信息，并加锁避免并发问题
        #     goods = Goods.objects.select_for_update().get(id=goods_id)
        #
        #     seckill_goods = SeckillGoods.objects.select_for_update().get(goods_id=goods_id)
        #     # 检查秒杀活动是否有效
        #     if not (seckill_goods.start_date<=now() <= seckill_goods.end_date):
        #         return Response({'code': 400, 'message': '秒杀活动无效或已结束'})
        #     if seckill_goods.stock_count<=0 or goods.goods_stock<=0:
        #         return Response({'code':400,'message':'库存不足'})
        #
        #     seckill_goods.stock_count-=1
        #     goods.goods_stock-=1
        #     seckill_goods.save()
        #     goods.save()
        #     order = Order.objects.create(
        #         user_id=user_id,
        #         goods_id=goods_id,
        #         delivery_addr_id=1,  # 示例：默认地址
        #         goods_name=goods.goods_name,
        #         goods_count=1,
        #         goods_price=seckill_goods.seckill_price,
        #         order_channel=1,  # 秒杀渠道
        #         status=0,  # 待支付
        #
        #     )
        #     # 创建秒杀订单并关联普通订单
        #     seckill_order = SeckillOrder.objects.create(
        #         user_id=user_id,
        #         goods_id=goods_id,
        #         order=order,
        #     )
        #     return Response({
        #         'code': 200,
        #         'message': '秒杀成功',
        #         'data': {
        #             'order_id': order.id,
        #             'seckill_order_id': seckill_order.id,
        #         }
        #     })
        # except Goods.DoesNotExist:
        #     return Response({'code': 400, 'message': '商品不存在'})
        # except SeckillGoods.DoesNotExist:
        #     return Response({'code': 400, 'message': '秒杀商品不存在'})
        # except Exception as e:
        #     # 捕获其他异常，返回友好提示
        #     return Response({'code': 500, 'message': f'服务器错误: {str(e)}'})